import os
from datetime import datetime
from flask import request, make_response
from flask import send_file
from flask_restful import Resource
from werkzeug.security import safe_join

from config.env_default import world_env
from util import res_util
from util.file_util import get_uuid_file_name


class FileApi2(Resource):

    def get(self, path):
        # 安全检查，防止目录遍历攻击
        filepath = safe_join(world_env.upload_file_path2, path)
        if not os.path.exists(filepath):
            return res_util.fail("404 文件存在")
        # 检查客户端是否请求下载
        download = request.args.get('download', 'false').lower() == 'true'
        last_modified = datetime.fromtimestamp(os.path.getmtime(filepath))
        if_modified_since = request.headers.get('If-Modified-Since')
        if if_modified_since:
            if_modified_since = datetime.strptime(if_modified_since, '%a, %d %b %Y %H:%M:%S GMT')
            if last_modified <= if_modified_since:
                return '', 304  # Not Modified
        response = make_response(send_file(filepath))
        response.headers['Last-Modified'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT')
        response.headers['Cache-Control'] = 'public, max-age=31536000'  # 1年缓存
        response.headers['ETag'] = os.path.getsize(filepath)  # 简单ETag实现
        if download:
            response.headers['Content-Disposition'] = f'attachment; filename={path.split(' / ')[-1]}'
        return response

    def post(self):
        file = request.files["file"]
        file_name = get_uuid_file_name(file.filename)
        file.save(os.path.join(world_env.upload_file_path2, file_name))
        return res_util.success(f"{world_env.file_url_prefix}/api/file/FileApi2/{file_name}")


if __name__ == '__main__':

    print(os.listdir())
    for root, dirs, files in os.walk(".", topdown=False):
        for name in files:
            print(os.path.join(root, name))
        for name in dirs:
            print(os.path.join(root, name))
    root, dirs, files = os.walk("").__next__()
    print("--", root, dirs, files)
